package com.tanhua.server.service;

import com.tanhua.autoconfig.template.AipFaceTemplate;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.UserInfoVo;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Service
public class UserInfoService {

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private AipFaceTemplate aipFaceTemplate;

    /*首次登录--完善信息*/
    public void save(UserInfo userInfo) {
        userInfoApi.save(userInfo);
    }


    /*用户资料---补充头像*/
    public void updateHead(MultipartFile headPhoto) throws IOException {
        //获取当前用户id
        Long userId = UserHolder.getUserId();
        //上传图片至阿里云
        String imageUrl = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
        //调用百度云判断是否包含人脸
        boolean detect = aipFaceTemplate.detect(imageUrl);
        //不包含人脸则抛出异常
        if (!detect) {
            throw new BusinessException(ErrorResult.faceError());
        } else {
            //包含人脸则更新
            UserInfo userInfo = new UserInfo();
            userInfo.setId(userId);
            userInfo.setAvatar(imageUrl);
            userInfoApi.update(userInfo);
        }
    }

    /*用户资料---读取*/
    public UserInfoVo findById(Long id) {
        UserInfo userInfo = userInfoApi.findById(id);
        UserInfoVo userInfoVo = new UserInfoVo();
        //将userInfo的属性copy至userInfoVo,只会copy同名同类型的属性
        BeanUtils.copyProperties(userInfo, userInfoVo);
        //因为数据库中的age为Integer类型，而接口文档为String类型，需要单独处理
        if(userInfo.getAge()!=null) {
            userInfoVo.setAge(userInfo.getAge().toString());
        }
        return userInfoVo;
    }

    /*用户资料---保存(更新)*/
    public void update(UserInfo userInfo) {
        userInfoApi.update(userInfo);
    }
}